﻿Imports System.ComponentModel
Imports System.Net.NetworkInformation
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Melsec
Public Class frmJCJ
    Private g_szInitFileName As String
    Private logfile As ILogNet
    Private plc As MelsecMcNet
    Private PLC_IP As String = "172.16.20.142"
    Private PLC_Port As Integer = 6200
    Dim objDB As New clsJCJ
    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub 关闭ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关闭ToolStripMenuItem.Click
        If MsgBox("关闭画面后将无法监控挤出机的情况，确定要关闭吗？", MsgBoxStyle.YesNo, "挤出机监控") = MsgBoxResult.Yes Then
            RemoveHandler Me.FormClosing, AddressOf frmJCJ_FormClosing
            NotifyIcon1.Dispose()
            Close()
        End If
    End Sub

    Private Sub frmJCJ_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\JCJ.ini"
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        connectDB()
        PLC_IP = GetIniFile("PLC", "IP", "", Me.g_szInitFileName)
        PLC_Port = GetIniFile("PLC", "PORT", "", Me.g_szInitFileName)

        '读PLC
        plc = New MelsecMcNet
        With plc
            .IpAddress = PLC_IP
            .Port = PLC_Port
            .SetPersistentConnection()
        End With

        readPLC()
        Dim dt As DataTable = objDB.selectALL()
        dgv.DataSource = dt
        Timer1.Interval = 60 * 1000
        Timer1.Start()
    End Sub
    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub
    Private Sub readPLC()

        Dim ping = New Net.NetworkInformation.Ping()
        Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(PLC_IP)

        If pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
            objDB.record_JCJ_Status(0)
        Else
            objDB.record_JCJ_Status(2)
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        readPLC()
        Dim dt As DataTable = objDB.selectALL()
        dgv.DataSource = dt
    End Sub


    Private Sub NotifyIcon1_DoubleClick(sender As Object, e As EventArgs) Handles NotifyIcon1.DoubleClick
        Me.Show()
    End Sub

    Private Sub frmJCJ_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        Me.Hide()
        e.Cancel = True
    End Sub
End Class

Public Class clsJCJ
    Public Function record_JCJ_Status(_status As Integer) As Integer
        Dim Sql As String = String.Empty
        Try
            If _status = 0 Then

                Sql = "select * from sf.b_jcj_power where off_dt is null"
                Dim dt As DataTable = DBacs.ExecuteSql(Sql, -1)
                If dt.Rows.Count = 0 Then
                    Sql = "INSERT INTO sf.b_jcj_power(on_dt) VALUES (?)"
                    Return DBacs.ExecuteUpdateSql(Sql, -1, Now())
                End If

            ElseIf _status = 2 Then
                Sql = "update sf.b_jcj_power "
                Sql &= "set off_dt=? "
                Sql &= "where  off_dt is null "
                Return DBacs.ExecuteUpdateSql(Sql, -1, Now())
            End If
            Return 1
        Catch ex As Exception
            Return -2
        End Try

    End Function
    Public Function selectALL() As DataTable
        Dim szSql As String = ""
        szSql &= " select * from sf.b_jcj_power order by on_dt DESC"

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            selectALL = New DataTable
        Else
            selectALL = dt
        End If
    End Function
End Class
